<template>
  <el-card>
    <el-form
      label-width="100px"
      :model="skuFormData"
      :rules="skuDataRules"
      ref="formDom"
    >
      <el-form-item label="SPU名称"> {{ skuFormData.skuName }} </el-form-item>
      <el-form-item label="skuName" prop="skuName">
        <el-input placeholder="请输入SKU名称" v-model="skuFormData.skuName" />
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          :min="0"
          controls-position="right"
          class="sku-input-number"
          v-model="skuFormData.price"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input v-model="skuFormData.weight" />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          type="textarea"
          placeholder="请输入规格描述"
          v-model="skuFormData.skuDesc"
        />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row class="row">
          <el-col
            :xs="24"
            :md="12"
            :lg="8"
            :xl="6"
            class="col"
            v-for="(item, index) in skuAttrValueList"
            :key="index"
          >
            <div class="wrap">
              <div class="spanLeft">{{ item.attrName }}</div>
              <el-select
                class="select"
                v-model="skuFormData.skuAttrValueList[index]"
              >
                <el-option
                  :value="`${item.id}:${item.attrName}:${obj.id}:${obj.valueName}`"
                  v-for="obj in item.attrValueList"
                  :key="obj.id"
                  :label="obj.valueName"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row class="row">
          <el-col
            :xs="24"
            :md="12"
            :lg="8"
            :xl="6"
            class="col"
            v-for="(item, index) in skuSaleAttrValueList"
            :key="index"
          >
            <div class="wrap">
              <div class="spanLeft">{{ item.saleAttrName }}</div>
              <el-select
                class="select"
                v-model="skuFormData.skuSaleAttrValueList[index]"
              >
                <el-option
                  v-for="obj in item.spuSaleAttrValueList"
                  :key="obj.saleAttrValueName"
                  :label="obj.saleAttrValueName"
                  :value="`${item.id}:${item.saleAttrName}:${obj.id}:${obj.saleAttrValueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="spuImages"
          style="width: 100%"
          border
          @selection-change="selectImage"
        >
          <el-table-column width="70" type="selection" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <el-image
                style="width: 100px; height: 100px"
                :src="row.imgUrl"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag type="success" v-if="row.isDefault === '1'">默认</el-tag>
              <el-button type="primary" v-else @click="setDefault(row)"
                >设置默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button type="primary" @click="emit('toggle', 0)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XSpuAddIem",
};
</script>

<script lang="ts" setup>
import { reactive, onMounted, ref } from "vue";
import { useSpuStore } from "@/stores/spu";
import { reqProducType } from "@/api/product/attr";
import type { productType } from "@/api/product/model/index";
import type {
  ArraySpuSaleAttrList,
  spuImageList,
} from "@/api/product/model/spuType";
import { reqSpuSalesList, reqSpuSaleImage } from "@/api/product/spu";
import type { skuType, skuImageListType } from "@/api/product/model/skuType";
import { reqAddSku } from "@/api/product/sku";
import { ElMessage } from "element-plus";
const spuStore = useSpuStore();
const emit = defineEmits(["toggle"]);
const skuSaleAttrValueList = ref<ArraySpuSaleAttrList>([]);
const skuAttrValueList = ref<productType[]>([]);
const spuImages = ref<spuImageList[]>([]);
const formDom = ref();
const skuFormData = reactive<skuType>({
  skuName: spuStore.$state.skuInfo.spuName,
  price: 0,
  weight: "",
  skuDesc: "",
  skuAttrValueList: [
    // {
    // attrId: 0, // 属性名id
    // attrName: "string", // 属性名名称
    // // id: 0, （不要）
    // // skuId: 0,（不要）
    // valueId: 0, // 属性值id
    // valueName: "string", // 属性值名称
    // },
  ],
  skuSaleAttrValueList: [
    // {
    //   saleAttrId: 0, // 销售属性名id
    //   saleAttrName: "string", // 销售属性名名称
    //   saleAttrValueId: 0, // 销售属性值id
    //   saleAttrValueName: "string", // 销售属性值名称
    //   // id: 0, （不要）
    //   // skuId: 0, （不要）
    //   // spuId: 0, （不要）
    // },
  ],
  skuImageList: [
    // {
    //   id: 0,
    //   imgName: "",
    //   imgUrl: "",
    //   isDefault: "", // 指定是否是默认图片
    // },
  ],
  skuDefaultImg: "", // 默认图片地址
});
function validatorWeight(rule: any, value: any, callback: any) {
  if (!value) {
    callback(new Error("请输入重量!!"));
  }
  if (!Number(value)) {
    callback(new Error("重量只能是数字哦!!"));
  }
  callback();
}
const skuDataRules = reactive({
  skuName: [
    {
      required: true,
      message: "请输入skuName",
      trigger: "blur",
    },
  ],
  price: [
    {
      required: true,
      message: "请输入价格",
      trigger: "change",
    },
  ],
  weight: [
    {
      required: true,
      trigger: "blur",
      validator: validatorWeight,
    },
  ],
  skuDesc: [
    {
      required: true,
      message: "请填写描述",
      trigger: "blur",
    },
  ],
  skuAttrValueList: [
    {
      required: true,
      message: "请选择平台属性",
    },
  ],
  skuSaleAttrValueList: [
    {
      required: true,
      message: "请选择销售属性",
    },
  ],
  skuImageList: [
    {
      required: true,
      validator: validatorMethod,
    },
  ],
});
function validatorMethod(rule: any, value: skuImageListType[], callback: any) {
  if (!value.length) {
    callback(new Error("请至少选择一张图片"));
    return;
  }
  if (!value.some((item: skuImageListType) => item.isDefault === "1")) {
    callback(new Error("请选择默认图片"));
  }
  callback();
}
// {
//   "category3Id": 0,
//   "createTime": "2022-11-23T04:23:44.197Z",
//   "id": 0,
//   "isSale": 0,
//   "price": 0,
//   "skuAttrValueList": [
//     {
//       "attrId": 0,
//       "attrName": "string",
//       "id": 0,不要
//       "skuId": 0,不要
//       "valueId": 0,
//       "valueName": "string"
//     }
//   ],
//   "skuDefaultImg": "string",
//   "skuDesc": "string",
//   "skuImageList": [
//     {
//       "id": 0,
//       "imgName": "string",
//       "imgUrl": "string",
//       "isDefault":"string",
//       "skuId": 0,不要
//       "spuImgId": 0不要
//     }
//   ],
//   "skuName": "string",
//   "skuSaleAttrValueList": [
//     {
//       "id": 0,
//       "saleAttrId": 0,
//       "saleAttrName": "string",
//       "saleAttrValueId": 0,
//       "saleAttrValueName": "string",
//       "skuId": 0,
//       "spuId": 0
//     }
//   ],
//   "spuId": 0,
//   "tmId": 0,
//   "weight": "string"
// }
onMounted(async () => {
  interface obj {
    category1Id: number;
    category2Id: number;
    category3Id: number;
  }
  const { category1Id, category2Id, category3Id } = spuStore.$state;
  const result = await reqProducType({
    category1Id,
    category2Id,
    category3Id,
  } as obj);
  // console.log(result);
  skuAttrValueList.value = result as any;
});
onMounted(async () => {
  const result = await reqSpuSalesList(spuStore.$state.skuInfo.id as number);
  skuSaleAttrValueList.value = result;
});
onMounted(async () => {
  const result = await reqSpuSaleImage(spuStore.$state.skuInfo.id as number);
  spuImages.value = result.map((item) => {
    return { ...item, isDefault: "0" };
  });
});
function selectImage(selection: spuImageList[]) {
  skuFormData.skuImageList = selection as skuImageListType[];
  console.log(skuFormData);
}
function setDefault(row: skuImageListType) {
  spuImages.value.forEach((item) => {
    item.isDefault = "0";
  });
  row.isDefault = "1";
  // skuFormData.skuImageList = spuImages.value;
}
async function confirm() {
  try {
    await formDom.value.validate();

    const skuAttrValueList = (skuFormData.skuAttrValueList as [])
      .filter(Boolean)
      .map((item) => {
        const [attrId, attrName, valueId, valueName] = (item as string).split(
          ":"
        );
        return { attrId, attrName, valueId, valueName };
      });
    const skuSaleAttrValueList = skuFormData.skuSaleAttrValueList.map(
      (item) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = (
          item as string
        ).split(":");
        return { saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName };
      }
    );
    const data = {
      ...skuFormData,
      skuAttrValueList,
      skuSaleAttrValueList,
    };
    // console.log(data);
    await reqAddSku(data as any);
    ElMessage.success("添加sku成功!!!");
    emit("toggle", 0);
  } catch (error) {
    console.log("表单验证失败!!", error);
  }
}
</script>

<style scoped>
.row {
  width: 100%;
}
.wrap {
  width: 100%;
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start;
}
.spanLeft {
  text-align: right;
  width: 100px;
  flex: 1;
  margin-right: 10px;
}
.sku-input-number {
  width: 100%;
}
/* .row {
  transform: translateX(-100px);
} */
</style>
